var win = window,
	doc = document,
	apiUrl = 'http://api-iminproject.rhcloud.com/',
	debug = function( message ) { return console.log( message ) };

$( doc ).on( 'ready', function()
{
    tagSearch();
    renderEventsList( 'latest' );
	viewEvent();
	gMaps();
	eventCreate();
	// fakeEvent();
} );

$( doc ).on( 'click', function( e )
{
	var oTarget = e.target,
		tagSearch = doc.getElementById('tag_search'),
		tagResults = doc.getElementById('tagResults');

	if( oTarget.tagName.toLowerCase().toLowerCase() === 'a' && oTarget.getAttribute( 'href' ) === '#' )
	{
		e.preventDefault();
	}
	else if( tagSearch && ( oTarget !== tagSearch && oTarget !== tagResults ) )
	{
    	tagResults.innerHTML = '';
	}
} );

function loadTemplate( sId, oData )
{
	var template = _.template( doc.getElementById( sId ).innerHTML, { data: oData } );
	doc.getElementById( 'content' ).innerHTML = template;
}

function getDataFromPath( sPath, oObject )
{
	var oPathData = oObject,
		aParts = sPath.split( '.' ),
		nPartsLen = aParts.length,
		i = 0;
		for( ; i < nPartsLen; i++ )
		{
			oPathData = oPathData[aParts[i]];
		}
		return oPathData;
}

function apiCall( resource, fpCallback, method, data )
{
	var method = method || 'get';
	var data = data || null;

	$.ajax(
	{
		url: apiUrl + resource,
		type: method,
		dataType: 'json',
		data: data
	} )
	.done( fpCallback )
	.fail( function ( oError ) { debug( oError.statusText ) });
}

function gMaps()
{
	var placeSearch, autocomplete;

	if( !!document.getElementById('eventAddress') )
	{
		function initialize() {
		  // Create the autocomplete object, restricting the search
		  // to geographical location types.
		  autocomplete = new google.maps.places.Autocomplete(
		      /** @type {HTMLInputElement} */(document.getElementById('eventAddress')),
		      { types: ['geocode'] });
		  // When the user selects an address from the dropdown,
		  // populate the address fields in the form.

			google.maps.event.addListener(autocomplete, 'place_changed', function() {
				var inputLocation = autocomplete.getPlace().geometry.location.toString(),
					location = inputLocation.split(',');

				inputLocation = location[0].slice(1) + ',' + location[1].slice(1);
				inputLocation = inputLocation.slice( 0, inputLocation.length-1 );

				$('#eventCoords').val(inputLocation);
			} );
		}

		initialize();
	}
}

function eventCreate()
{
	var createEventBtn = $('#create-event-btn');

	if( createEventBtn )
	{
		var eventTitle = $('#eventTitle'),
			eventAddress = $('#eventAddress'),
			eventCoords = $('#eventCoords'),
			eventDate = $('#eventDate'),
			eventPrice = $('#eventPrice'),
			eventPriceDiscount = $('#eventPriceDiscount'),
			eventPeople = $('#eventPeople'),
			eventUrl = $('#eventUrl'),
			eventDesc = $('#eventDesc'),
			eventEmail = $('#eventEmail'),
            tag = $('#tag_search'),
			sendedData;

		createEventBtn.click( function( e )
		{
			if( eventTitle.val() && eventAddress.val() && eventDate.val() && eventPrice.val() && eventPeople.val()
				&& eventPriceDiscount.val() /*&& eventUrl.val() */ && eventDesc.val() && validateEmail( eventEmail.val() ) && $(tag).attr( 'data-id' ))
			{
				sendedData = {
					"title": eventTitle.val(),
					"address": eventAddress.val(),
					"coords": eventCoords.val(),
					"date": eventDate.val().split('T').join(' ') + ':00',
					"indivual_price": eventPrice.val(),
					"group_price": eventPriceDiscount.val(),
					"minimum_persons": eventPeople.val(),
					"event_url": eventUrl.val(),
					"description": eventDesc.val(),
					"mail": eventEmail.val(),
                    "subscribers": 1,
                    "tag": $(tag).attr( 'data-id' )
				};

				apiCall( 'discounts', function( oResponse )
				{
					doc.location = '?section=event-view&id=' + oResponse.id;

				}, 'post', sendedData );
			}
			else
			{
				alert("Please fill all event information.");
			}
		});
	}
}
function fakeEvent()
{
	$('#eventTitle').val( 'Algo' );
	$('#eventDate').val( '2014-01-01T20:04' );
	$('#eventAddress').val( 'Barcelona' );
	$('#eventCoords').val( '41.3850639,2.1734034999999494' );
	$('#eventPrice').val( '2' );
	$('#eventPriceDiscount').val( '1' );
	$('#eventPeople').val( '10' );
	$('#eventUrl').val( 'http://www.google.com' );
	$('#eventDesc').val( 'ASD asd asd asd asd asd' );
	$('#eventEmail').val( 'asdasd@casdasd.com' );
}

function renderEventsList( sType, sId )
{
	var containerEventsList = doc.getElementById( sType + '-events'),
		query = ( sType === 'latest') ? 'discounts?max=10&status=news' : 'tags/' + sId + '/discounts';

	if( containerEventsList )
	{
		apiCall( query, function( data )
		{
			var list = '',
            	len = data.length,
            	description;

            for(var i = 0; i < len; i++)
            {
            	description = ( data[i].description.length > 150 ) ? data[i].description.slice( 0, 180 ) + '...' : data[i].description;

                list += '<div class="list-group-item event_list_item" data-event-id="' + data[i].id + '"><div class="row-content"><div class="least-content">' + data[i].date_elapsed  + '</div><h4 class="list-group-item-heading">' + data[i].title + '</h4><p class="list-group-item-text">' + description + '</p></div></div>';
            }
            if( len <= 0 )
            {
            	list = '<p class="page-content">No events to show. Please try later or create a new one!</p>';
            }
            doc.getElementById( sType + '-events-list').innerHTML = list;

			if( doc.getElementById( 'searched-events-query') )
			{
				doc.getElementById( 'searched-events-query').innerHTML = $('#tag_search').val();
			}
			viewEventClicked();
			$( containerEventsList ).fadeIn();
		} );
	}
}

function viewEventClicked()
{
    $('.event_list_item').click(function()
    {
        doc.location = '?section=event-view&id=' + this.dataset.eventId;
    });
}

function tagSearch()
{
	var tagSearch = $('#tag_search'),
		tagResults = doc.getElementById('tagResults');

    tagSearch
    	.focus( function()
    	{
    		$('#search-icon').addClass( 'search-icon-focus' );
    	})
    	.blur( function()
    	{
    		$('#search-icon').removeClass( 'search-icon-focus' );
    	})
    	.keyup(tagSearchCall)
    	.keypress(function(e)
	   	{
	   		var oTarget = e.target;

			if(e.which == 13)
			{
                if (!$(oTarget).attr( 'data-id' ))
                {
                    $('#searched-events').css('display', 'none');
                    $('#searched-events-list').html('');
                }
                else{
                    renderEventsList( 'searched', $(oTarget).attr( 'data-id' )  );
                }
			}
		} );

	$( tagResults ).click( 'li', function( e )
    {
    	var oTarget = e.target;
    	if( oTarget.tagName.toLowerCase() === 'li' )
		{
			tagSearch
				.attr( 'data-id', oTarget.value )
				.val( oTarget.innerHTML );

			tagResults.innerHTML = '';

			renderEventsList( 'searched', oTarget.value );
		}
	});
}

function tagSearchCall(e)
{
    var oElement = doc.getElementById('tag_search');
	var text = oElement.value;

    if (e.which !== 13)
    {
        $(oElement).attr( 'data-id', '' );
    }

    if (text.length > 0 && e.which !== 13)
    {
        apiCall('tags/search?title=' + text, function (data)
        {
            var list = "<ul>",
            	len = data.length;
            for(var i = 0; i < len; i++)
            {
                list += "<li class='search-tag' value='"+ data[i].id +"'>" + data[i].title + "</li>";
            }
            list += "</ul>";

            if (doc.getElementById('tag_search').value.length > 0) {
                doc.getElementById('tagResults').innerHTML = list;
            }
        });
    }
    else{
        doc.getElementById('tagResults').innerHTML = '';
    }
}

function viewEvent()
{
    if ( !!doc.getElementById( 'event-view-content' ) && 'event-view' == getParameterByName('section') )
    {
        var id = getParameterByName('id');

        apiCall('discounts/' + id, function(data)
        {
        	var tagTitle = '';
        	if( data.tag && data.tag.title )
        	{
        		tagTitle = '<blockquote><p><cite><i class="icon-material-more m-r" id="search-icon"></i>'+ data.tag.title + '</cite></p></blockquote>';
        	}
        	var discount = (1 -( data.group_price / data.indivual_price ) ) * 100,
        		sDiscount = '';
        	if( discount > 0 )
        	{
        		sDiscount = '  <span class="text-stroked"> ' + data.indivual_price + '€ </span> (' + Math.round( discount ) + '%)';
        	}
        	var result = '<h2 class="event-title">' + data.title + '</h2><div class="event-numbers"><div class="col-2"><p><strong>' + data.group_price + '€</strong>' + sDiscount + '</p></div><div class="col-2"><p><i class="icon-material-group m-r"></i>' + data.subscribers + ' / <strong>' + data.minimum_persons + '</strong></p></div></div><div class="event-numbers"><div class="col-2"><p><i class="icon-material-event m-r"></i> ' + data.date.slice(0, -3) + '</p></div><div class="col-2"><p><i class="icon-material-public m-r"></i> <a class="link" href="' + data.event_url + '" target="_blank">Page event</a></p></div></div></div><blockquote><p><i class="icon-material-chat m-r"></i> ' + data.description + '</p></blockquote><blockquote><p><cite><i class="icon-material-person-location m-r"></i> ' + data.address + '</cite></p></blockquote><div id="map-canvas" class="clearfix"></div>' + tagTitle;

            $('#event-view-content').html( result );

            $('#subscribe-event-btn').attr('data-id', data.id );
            $('#subscribe-event-btn').attr('data-subscribers', data.subscribers );

            if( data.coords )
            {
            	function initialize()
            	{
	              var coords = data.coords.split(',');
				  var myLatlng = new google.maps.LatLng(coords[0],coords[1]);
				  var mapOptions = {
				    zoom: 16,
				    center: myLatlng
				  }
				  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

				  var marker = new google.maps.Marker({
				  	position: myLatlng,
					map: map,
				  } );
				  document.getElementById('map-canvas').classList.add( 'map-box' );
				}
				initialize();
            }
            $('#event-view').fadeIn();
            subscribeEvent();
        });
    }
}

function validateEmail( email )
{
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

    return re.test( $.trim( email ) );
}

function subscribeEvent()
{
    $('#subscribe-event-btn').click(function()
    {
    	if( $('#mail_subscription').val() === '' )
    	{
			openEmailInput();
    	}
    	else
    	{
    		ImInEvent();
    	}
    });

    $('#event-view-email')
        .focusout(function()
        {
        	$(this).css('display', 'none');
        	setTimeout( function() { $('#mail_subscription').val( '' ); }, 100 );
        } );

    $('#mail_subscription').keypress( function( e )
	{
		if( 13 == e.which )
		{
			ImInEvent();
		}
	} );

	function openEmailInput()
	{
        $('#event-view-email').fadeIn( function()
    	{
    		$('#mail_subscription').focus();
    	} );
    }

    function ImInEvent()
    {
        var event_id = $('#subscribe-event-btn').data('id'),
        	subscribers = $('#subscribe-event-btn').data('subscribers'),
        	data = {
	            subscribers: parseInt(subscribers, 10) + 1,
	            mail: $('#mail_subscription').val(),
	            _method: 'PATCH'
	        };

        if( !!validateEmail( $('#mail_subscription').val() ) )
        {
         	$('#subscribe-event-btn')
        		.addClass( 'no-events' )
        		.html( 'Please wait...' );

        		setTimeout( function()
        		{
        			alert( "You are subscribed to the event!");

	            	doc.location = '?section=event-view&id=1' ;
        		}, 2000 );

        	    apiCall('discounts/' + event_id, function (oResponse)
        	    {
        	        alert( "You are subscribed to the event!");

	                doc.location = '?section=event-view&id=' + oResponse.id;
	            }, 'POST', data);
        }
        else
        {
        	alert("Please type a correct email");
        }
    }
}

function setStorageData( oObject, sKey )
{
	localStorage.setItem( sKey, JSON.stringify( oObject, null, '\t' ) );
}
function getStorageData( sKey )
{
	return JSON.parse( localStorage.getItem( sKey ) );
}

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}